package com.cloudeasy.provider.service.impl;

import com.cloudeasy.PublicUtil;
import com.cloudeasy.base.dto.LoginAuthDto;
import com.cloudeasy.base.enums.ErrorCodeEnum;
import com.cloudeasy.provider.model.constant.UacConstant;
import com.cloudeasy.provider.model.domain.UacUser;
import com.cloudeasy.provider.model.dto.user.LoginRespDto;
import com.cloudeasy.provider.model.exceptions.UacBizException;
import com.cloudeasy.provider.model.vo.MenuVo;
import com.cloudeasy.provider.security.SecurityUtils;
import com.cloudeasy.provider.service.UacLoginService;
import com.cloudeasy.provider.service.UacMenuService;
import com.cloudeasy.provider.service.UacUserService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Create By 郭金宝 on 2019/2/13.<br>
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UacLoginServiceImpl implements UacLoginService {

    @Resource
    private UacUserService uacUserService;
    @Resource
    private UacMenuService uacMenuService;

    @Override
    public LoginRespDto loginAfter(Long applicationId) {
        LoginRespDto loginRespDto = new LoginRespDto();
        String loginName = SecurityUtils.getCurrentLoginName();
        if (StringUtils.isEmpty(loginName)) {
            log.error("操作超时, 请重新登录 loginName={}", loginName);
            Preconditions.checkArgument(StringUtils.isNotEmpty(loginName), "操作超时, 请重新登录");
        }

        UacUser uacUser = uacUserService.findByLoginName(loginName);
        if (PublicUtil.isEmpty(uacUser)) {
            log.info("找不到用户信息 loginName={}", loginName);
            throw new UacBizException(ErrorCodeEnum.UAC10011002, loginName);
        }

        LoginAuthDto loginAuthDto = this.getLoginAuthDto(uacUser);
        List<MenuVo> menuVoList = uacMenuService.getMenuVoList(uacUser.getId(), applicationId);
        if (PublicUtil.isNotEmpty(menuVoList) && UacConstant.MENU_ROOT.equals(menuVoList.get(0).getMenuCode())) {
            menuVoList = menuVoList.get(0).getSubMenu();
        }
        loginRespDto.setLoginAuthDto(loginAuthDto);
        loginRespDto.setMenuList(menuVoList);
        return loginRespDto;
    }

    private LoginAuthDto getLoginAuthDto(UacUser uacUser) {
        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setUserId(uacUser.getId());
        loginAuthDto.setUserName(uacUser.getUserName());
        loginAuthDto.setLoginName(uacUser.getLoginName());
        return loginAuthDto;
    }


}
